import DataGrid from 'devextreme-react/data-grid';
import moment from 'moment';
import React, { useImperativeHandle, useMemo, useRef, useState } from 'react';
import * as ReactDOMClient from 'react-dom/client';
import { useModel } from 'umi';
import { CpasIcon, DevPopup } from '~/public/cpas-ui';
// import DataRow from './dataRow';
// import DiffCell from '../Cell';
import notify from 'devextreme/ui/notify';
import '../index.less';
import { deleteTable } from '../service';
const InternalNbwl = React.forwardRef((props: any, ref: any) => {
  const { initialState } = useModel('@@initialState');
  const { username } = initialState?.curUser as API.CurUser;
  const { dbname } = initialState?.curPart as API.curPart;

  const { DevData, data_id, setNbwltjData } = props;
  const [columnsData, setColumnsData] = useState<any[]>([]);
  const [columnsBtn, setColumnsBtn] = useState<boolean>(true);

  const DataRef = useRef<any>();
  const eventsSaveData = useRef<any>([]);
  const eventsNewRowKey = useRef<any>([]);
  const DeleteRef = useRef<any>([]);

  const comfirRef = useRef<any>([]);
  const editAllowUpdating = (e: any) => {
    console.log(e);
    if (e.row.data.from_type === '底稿') {
      return false;
    } else {
      return e.row.data.updateFlag !== 0;
    }
  };

  const deleteRow = async (guid: string) => {
    DeleteRef.current.show({
      title: '提示',
      okCallback: async () => {
        eventsSaveData.current.push({ rowState: 'delete', guid: guid });
        setNbwltjData((item: any) => {
          const newItemData: any[] = [...item];
          const resFind = newItemData.filter((data: any) => data.guid !== guid);
          return resFind;
        });
        let dd: any = {
          dbname: dbname,
          tableName: 'BB_ReportIntercourse',
          guid: guid,
        };

        const res = await deleteTable(dd);
        if (res.ok) {
          notify(`删除成功！`, 'success', 2000);
        } else {
          notify(`删除失败！`, 'error', 2000);
        }
      },
    });
  };
  useImperativeHandle(ref, () => ({
    getCurrentDevUpdateData: async () => {
      return eventsSaveData.current;
    },
    getCurrentDevTable: () => {
      return DataRef.current.instance;
    },
    clearCurrentDevUpdateData: () => {
      eventsSaveData.current = [];
      eventsNewRowKey.current = [];
    },
    updateSetData: (colData: any) => {
      setColumnsData(colData);
      setColumnsBtn(false);
    },
  }));

  const rowStateChange = (rowData: any) => {
    const { data, key, type } = rowData;
    let newData: any;
    const baseData = { editDate: moment().format('YYYY-MM-DD HH:mm:ss'), editUser: username };
    let addbaseData = {
      ...baseData,
      data_id: data_id,
      rowState: 'insert',
      from_type: '手动添加',
      updateFlag: 1,
    };
    const newKey = eventsNewRowKey.current.find((item: any) => item === key);
    if (newKey) {
      newData = {
        ...data,
        ...addbaseData,
      };
    } else {
      if (type === 'insert') {
        newData = {
          ...data,
          ...addbaseData,
        };
        eventsNewRowKey.current.push(data.guid);
      } else if (type === 'update') {
        newData = { ...data, ...baseData, rowState: 'update', where: { guid: key } };
      } else {
        newData = { ...data, rowState: 'delete', guid: key };
      }
    }

    return newData;
  };

  const saveData = (e: any) => {
    if (e.changes.length) {
      const { key } = e.changes[0];
      const newData = rowStateChange(e.changes[0]);

      const resFind = eventsSaveData.current.find((data: any) => data.guid && data.guid === key);
      if (resFind) {
        // 修改更改的值
        eventsSaveData.current = eventsSaveData.current.map((item: { guid: string }) => {
          if (item.guid === key) {
            return newData;
          }
          return item;
        });
      } else {
        eventsSaveData.current.push(newData);
      }
      console.log('lijin', newData);
      // // 手动渲染
    }
  };
  return useMemo(() => {
    let realCol: any = [];
    // let c:any=[] ;

    // c= columnsData.map((a: any) => {return {...a,cellTemplate: DiffCell}}))
    if (columnsData.length === 0) return <>loading...</>;
    realCol = [
      ...columnsData.map((a: any) => {
        return { ...a, cssClass: 'cell-highlighted' };
      }),
      {
        caption: '行操作',
        width: 100,
        alignment: 'center',
        fixed: true,
        fixedPosition: 'right',
        cellTemplate: (cellElement: any, cellInfo: any) => {
          const { data, rowIndex, key } = cellInfo;
          return ReactDOMClient.createRoot(cellElement).render(
            <>
              {(data.updateFlag === 1 || data.updateFlag == null) && (
                <CpasIcon
                  type="icon-delete"
                  fontSize={16}
                  onClick={async () => {
                    await deleteRow(key);
                  }}
                />
              )}
            </>,
          );
        },
      },
    ];
    setColumnsBtn(true);
    return (
      <>
        <DevPopup.Default ref={DeleteRef} width={80} height={200}>
          {() => {
            return <span>是否要删除此记录？</span>;
          }}
        </DevPopup.Default>
        <DevPopup.Default ref={comfirRef} width={80} height={200}>
          {() => {
            return <span>是否要删除此记录？</span>;
          }}
        </DevPopup.Default>
        <DataGrid
          className="devHeadersCenter PaperDevSortableGrid"
          width="100%"
          height="100%"
          ref={DataRef}
          dataSource={DevData}
          // rowAlternationEnabled={true}
          headerFilter={{ visible: true }}
          // filterRow={true}
          keyExpr="guid"
          columns={realCol}
          showBorders={true}
          showRowLines={true}
          showColumnLines={true}
          repaintChangesOnly={true}
          onRowValidating={(e) => {
            if (e.brokenRules.length) {
              e.isValid = false;
              console.log('li', e);
              //   comfirRef.current.show({
              //     title: "提示",
              //   }
              //   )
              //   alert(e.brokenRules[0].message);
              //   notify(`${e.brokenRules[0].message}`,'error',700)
              return;
            }
          }}
          onSaved={saveData}
          sorting={{
            mode: 'single',
          }}
          pager={{
            displayMode: 'compact',
            visible: true,
            showNavigationButtons: true,
            showPageSizeSelector: true,
          }}
          editing={{
            mode: 'cell',
            startEditAction: 'click',
            allowUpdating: (e: any) => editAllowUpdating(e),
            // allowDeleting:true
          }}
          toolbar={{
            visible: false,
            items: [
              {
                widget: 'dxButton',
                name: 'addRowButton',
                cssClass: 'toolbardxButton',
                visible: true,
                location: 'after',
                options: {
                  text: '保存',
                },
              },
              {
                widget: 'dxButton',
                name: 'addRowButton',
                cssClass: 'toolbardxButton',
                visible: true,
                location: 'after',
                options: {
                  width: 150,
                  text: '设置自动对应',
                },
              },
            ],
          }}
        />
      </>
    );
  }, [DevData, columnsData, columnsBtn]);
});

export default InternalNbwl;
